package org.ysling.litemall.wx.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ysling.litemall.core.utils.ResponseUtil;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.service.LitemallGoodsService;
import org.ysling.litemall.db.service.LitemallRewardService;
import org.ysling.litemall.db.service.LitemallRewardTaskService;
import org.ysling.litemall.db.constant.RewardConstant;

import java.math.BigDecimal;

@Service
public class WxRewardService {

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallRewardTaskService rewardTaskService;
    @Autowired
    private LitemallRewardService rewardService;


    /**
     * 修改赏金状态和订单状态
     * @param reward
     */
    public void updateRewardStatus(LitemallReward reward){
        reward.setStatus(RewardConstant.STATUS_SUCCEED);
        if (rewardService.updateVersionSelective(reward) <= 0){
            throw new RuntimeException("赏金更新数据失败");
        }
        LitemallRewardTask rewardTask = rewardTaskService.findById(reward.getTaskId());
        if (rewardService.countReward(reward.getTaskId()) >= rewardTask.getRewardMember()){
            rewardTask.setStatus(RewardConstant.TASK_STATUS_SUCCEED);
        }
        BigDecimal decimal = BigDecimal.valueOf(rewardTask.getJoinersMember()).add(BigDecimal.ONE);
        rewardTask.setJoinersMember(decimal.intValue());
        if (rewardTaskService.updateVersionSelective(rewardTask) <= 0){
            throw new RuntimeException("赏金更新数据已失败");
        }
    }

    /**
     * 验证赏金是否有效
     * @return
     */
    public Object isReward(Integer rewardTaskId){
        if (rewardTaskId == null) {
            return ResponseUtil.badArgumentValue();
        }

        LitemallRewardTask rewardTask = rewardTaskService.findById(rewardTaskId);
        if (rewardTask == null) {
            return ResponseUtil.fail(800,"活动不存在");
        }

        if (!RewardConstant.TASK_STATUS_ON.equals(rewardTask.getStatus())){
            return ResponseUtil.fail(800,"活动已下线");
        }

        if (rewardService.countReward(rewardTask.getId()) >= rewardTask.getRewardMember()){
            return ResponseUtil.fail(800,"活动已结束");
        }

        LitemallGoods goods = goodsService.findById(rewardTask.getGoodsId());
        if (goods == null) {
            return ResponseUtil.fail(800,"商品不存在");
        }

        return null;
    }
}
